package cycling.taxi.com.ui.fragment;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.telephony.gsm.GsmCellLocation;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ZoomControls;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.TextureMapView;
import com.baidu.mapapi.model.LatLng;
import com.google.gson.Gson;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.Random;

import cycling.taxi.com.MyService;
import cycling.taxi.com.R;
import cycling.taxi.com.bean.LocationInfo;
import cycling.taxi.com.dialog.OnPositionListener;
import cycling.taxi.com.eventbus.CloseService;
import cycling.taxi.com.eventbus.SetTime;
import cycling.taxi.com.utils.LogUtil;
import cycling.taxi.com.utils.SPUtil;
import cycling.taxi.com.utils.ToastUtil;

/**
 * Created by Administrator on 2017/4/21.
 */

public class BaiduMapFrgt extends Fragment {

    private TextureMapView mMapView=null;
    String TAG ="---BaiduMapFrgt";
    private BaiduMap mBaiduMap;
    private LocationClient mLocationClient;
    private double mLatitude=0;//纬度
    private double mLongitude=0;//经度
    private double mLatitude1=0;//经度
    private double mLongitude1=0;//经度


    private MyService MyService;
    private Intent mIntent;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.frgt_baidu_map, container, false);
        mMapView = (TextureMapView)view.findViewById(R.id.bmapView);
        initData();
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

    }

    private void initData() {
        View child = mMapView.getChildAt(1);
        if (child != null && (child instanceof ImageView || child instanceof ZoomControls)){
            child.setVisibility(View.INVISIBLE);
        }
        //地图上比例尺
        mMapView.showScaleControl(false);
        // 隐藏缩放控件
        mMapView.showZoomControls(false);

        //绑定Service
        mIntent = new Intent(getActivity(),MyService.class);
        getActivity().startService(mIntent);
        getActivity().bindService(mIntent, conn, Context.BIND_AUTO_CREATE);
        //初始化定位
        initMapInfo();

    }


    private void initMapInfo() {
        //获得Map控制器
        mBaiduMap = mMapView.getMap();
        //开启定位图层
        mBaiduMap.setMyLocationEnabled(true);
        mBaiduMap.setIndoorEnable(true);
        // 定位初始化
        mLocationClient = new LocationClient(this.getContext());
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        option.setOpenGps(true); // 打开gps
        option.setCoorType("bd09ll"); // 设置坐标类型
        option.setScanSpan(1000);//扫描时间
        MyLocationListenner myListener = new MyLocationListenner();
        mLocationClient.registerLocationListener(myListener);// //注册监听函数
        mLocationClient.setLocOption(option);
        mLocationClient.start();

    }

    /**
     * 定位SDK监听函数
     */
    public class MyLocationListenner implements BDLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            //判断一下是否有定位信息,如果没有的话就说明没有绑定设备,只能定位到自己的位置
            if (mLongitude == 0 || mLatitude == 0) {
                Log.e("Tag没有绑定",String.valueOf(mLatitude)+String.valueOf(mLongitude));
                mLongitude = location.getLongitude();
                mLatitude = location.getLatitude();
            }


//            location.getLongitude();
            // map view 销毁后不在处理新接收的位置
            if (location == null || mMapView == null) {
                return;
            }
            mBaiduMap.clear();

            MyLocationData locData = new MyLocationData.Builder()
                    .accuracy(location.getRadius())
                    // 此处设置开发者获取到的方向信息，顺时针0-360====还有设置经纬度
                    .direction(100).latitude(mLatitude)
                    .longitude(mLongitude).build();

            mBaiduMap.setMyLocationData(locData);

            //设置经纬度

            LatLng point = new LatLng(mLatitude, mLongitude);
            MapStatus mMapStatus = new MapStatus.Builder().zoom(15).target(point).build();


            // 设置地图新状态
            MapStatusUpdate mMapStatusUpdate = MapStatusUpdateFactory.newMapStatus(mMapStatus);
            // 改变地图状态


            if (mLongitude != mLongitude1 || mLatitude != mLatitude1) {

                mBaiduMap.setMapStatus(mMapStatusUpdate);

                mLongitude1 = mLongitude;
                mLatitude1 = mLatitude;

            }

        }
    }

    @Subscribe
    public void onEvent(CloseService mag){
        LogUtil.d("关闭服务啦关闭服务啦关闭服务啦");
        if(conn!=null){
            getActivity().unbindService(conn);
            getActivity().stopService(mIntent);
        }
        conn=null;
        MyService=null;
    }

    @Override
    public void onResume() {
        Log.d(TAG,"onResume");
        mMapView.setVisibility(View.VISIBLE);
        mMapView.onResume();
        super.onResume();
    }

    @Override
    public void onPause() {
        Log.d(TAG,"onPause");
        mMapView.setVisibility(View.INVISIBLE);
        mMapView.onPause();
        super.onPause();

    }

    @Override
    public void onDestroy() {
        Log.d(TAG,"onDestroy");
        super.onDestroy();
        // 退出时销毁定位
        mLocationClient.stop();
        // 关闭定位图层
        mMapView.onDestroy();


        mBaiduMap.setMyLocationEnabled(false);
        mMapView = null;
        EventBus.getDefault().unregister(this);
    }

    ServiceConnection conn = new ServiceConnection() {
        @Override
        public void onServiceDisconnected(ComponentName name) {

        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            //返回一个MyService对象
            MyService = ((MyService.MsgBinder)service).getService();

            //注册回调接口来接收下载进度的变化
            MyService.setOnPositionListener(new OnPositionListener() {

                @Override
                public void onPosition(Integer statusCode, String beanJson) {
                    if (statusCode==null){
                        return;
                    }
                    Gson gson = new Gson();
                    if (statusCode==1){
                        ToastUtil.getInstance().toast("没有绑定");
                    }else {
                            SPUtil.getInstance().setBean("electricityInfo",beanJson);
                            Log.e("tag",beanJson);
                            LocationInfo locationInfo = gson.fromJson(beanJson, LocationInfo.class);
                            mLatitude=Double.parseDouble(locationInfo.getLatitude());
                            mLongitude=Double.parseDouble(locationInfo.getLongitude());
                            EventBus.getDefault().post(new SetTime(locationInfo));

                    }
                }
            });

        }
    };
}
